#include "../include/advancedinputhandler.h"
#include <QDebug>
#include <QtMath>

/**
 * @brief 高级输入处理器实现
 * 
 * 基于Qt6_Client_Development_Guide.md的指导实现
 * 提供延迟补偿、输入预测、防抖动等高级功能
 */

AdvancedInputHandler::AdvancedInputHandler(QObject *parent)
    : QObject(parent)
    , m_lastSentDirection(NONE)
    , m_pendingDirection(NONE)
    , m_predictedDirection(NONE)
    , m_lastInputTime(0)
    , m_lastSendTime(0)
    , m_networkLatency(50)  // 默认50ms延迟
    , m_debounceInterval(50)  // 默认50ms防抖动
    , m_inputBuffering(true)
    , m_inputPrediction(true)
    , m_inputCount(0)
    , m_confirmedInputs(0)
    , m_rejectedInputs(0)
    , m_averageLatency(0)
{
    // === 初始化定时器 ===
    m_bufferTimer = new QTimer(this);
    m_bufferTimer->setSingleShot(true);
    m_bufferTimer->setInterval(10);  // 10ms缓冲间隔
    connect(m_bufferTimer, &QTimer::timeout, this, &AdvancedInputHandler::processInputBuffer);
    
    m_debounceTimer = new QTimer(this);
    m_debounceTimer->setSingleShot(true);
    connect(m_debounceTimer, &QTimer::timeout, this, &AdvancedInputHandler::onDebounceTimer);
    
    qDebug() << "AdvancedInputHandler: 初始化高级输入处理器";
}

void AdvancedInputHandler::handleKeyPress(QKeyEvent* event)
{
    if (!event) return;
    
    Direction newDirection = keyToDirection(event->key());
    if (newDirection == NONE) {
        return;  // 不是方向键
    }
    
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    
    // === 防止反向移动 ===
    if (isOppositeDirection(newDirection, m_lastSentDirection)) {
        qDebug() << "AdvancedInputHandler: 忽略反向移动" << newDirection;
        emit inputRejected(newDirection, "反向移动");
        return;
    }
    
    // === 防抖动检查 ===
    if (newDirection == m_lastSentDirection && 
        (currentTime - m_lastSendTime) < m_debounceInterval) {
        qDebug() << "AdvancedInputHandler: 防抖动忽略重复输入" << newDirection;
        return;
    }
    
    // === 创建输入事件 ===
    InputEvent inputEvent(newDirection, currentTime);
    m_inputQueue.enqueue(inputEvent);
    m_inputCount++;
    
    qDebug() << "AdvancedInputHandler: 接收输入" << newDirection << "队列大小:" << m_inputQueue.size();
    
    // === 输入预测 ===
    if (m_inputPrediction) {
        predictMovement(newDirection);
    }
    
    // === 处理输入 ===
    if (m_inputBuffering) {
        // 启动缓冲定时器
        if (!m_bufferTimer->isActive()) {
            m_bufferTimer->start();
        }
        m_pendingDirection = newDirection;
    } else {
        // 立即发送
        sendDirectionChange(newDirection);
    }
    
    m_lastInputTime = currentTime;
}

void AdvancedInputHandler::handleKeyRelease(QKeyEvent* event)
{
    // 对于Snake游戏，按键释放通常不需要特殊处理
    Q_UNUSED(event)
}

void AdvancedInputHandler::setLatencyCompensation(int latencyMs)
{
    m_networkLatency = qMax(0, latencyMs);
    qDebug() << "AdvancedInputHandler: 设置延迟补偿" << m_networkLatency << "ms";
}

void AdvancedInputHandler::setInputBuffering(bool enabled)
{
    m_inputBuffering = enabled;
    qDebug() << "AdvancedInputHandler: 输入缓冲" << (enabled ? "启用" : "禁用");
    
    if (!enabled && m_bufferTimer->isActive()) {
        m_bufferTimer->stop();
        processInputBuffer();
    }
}

void AdvancedInputHandler::setDebounceInterval(int intervalMs)
{
    m_debounceInterval = qMax(0, intervalMs);
    qDebug() << "AdvancedInputHandler: 设置防抖动间隔" << m_debounceInterval << "ms";
}

void AdvancedInputHandler::setInputPrediction(bool enabled)
{
    m_inputPrediction = enabled;
    qDebug() << "AdvancedInputHandler: 输入预测" << (enabled ? "启用" : "禁用");
}

void AdvancedInputHandler::validateServerResponse(Direction serverDirection, qint64 serverTimestamp)
{
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    
    // === 查找对应的输入事件 ===
    bool found = false;
    for (auto it = m_inputQueue.begin(); it != m_inputQueue.end(); ++it) {
        if (it->direction == serverDirection && !it->processed) {
            // 找到匹配的输入
            it->processed = true;
            found = true;
            
            // 计算延迟
            int latency = currentTime - it->timestamp;
            m_averageLatency = (m_averageLatency + latency) / 2;
            
            m_confirmedInputs++;
            emit inputConfirmed(serverDirection, latency);
            
            qDebug() << "AdvancedInputHandler: 输入确认" << serverDirection << "延迟:" << latency << "ms";
            break;
        }
    }
    
    if (!found) {
        qDebug() << "AdvancedInputHandler: 未找到匹配的输入事件" << serverDirection;
    }
    
    // === 清理已处理的事件 ===
    while (!m_inputQueue.isEmpty() && m_inputQueue.head().processed) {
        m_inputQueue.dequeue();
    }
}

void AdvancedInputHandler::confirmInput(Direction direction, qint64 timestamp)
{
    validateServerResponse(direction, timestamp);
}

void AdvancedInputHandler::processInputBuffer()
{
    if (m_pendingDirection != NONE) {
        sendDirectionChange(m_pendingDirection);
        m_pendingDirection = NONE;
    }
}

void AdvancedInputHandler::reset()
{
    qDebug() << "AdvancedInputHandler: 重置输入状态";
    
    m_lastSentDirection = NONE;
    m_pendingDirection = NONE;
    m_predictedDirection = NONE;
    
    m_inputQueue.clear();
    
    m_bufferTimer->stop();
    m_debounceTimer->stop();
    
    // 重置统计
    m_inputCount = 0;
    m_confirmedInputs = 0;
    m_rejectedInputs = 0;
    m_averageLatency = 0;
}

void AdvancedInputHandler::onDebounceTimer()
{
    // 防抖动定时器到期，可以处理新的输入
    qDebug() << "AdvancedInputHandler: 防抖动定时器到期";
}

// === 私有方法实现 ===

AdvancedInputHandler::Direction AdvancedInputHandler::keyToDirection(int key)
{
    switch (key) {
    case Qt::Key_W:
    case Qt::Key_Up:
        return UP;
    case Qt::Key_S:
    case Qt::Key_Down:
        return DOWN;
    case Qt::Key_A:
    case Qt::Key_Left:
        return LEFT;
    case Qt::Key_D:
    case Qt::Key_Right:
        return RIGHT;
    default:
        return NONE;
    }
}

bool AdvancedInputHandler::isOppositeDirection(Direction dir1, Direction dir2)
{
    if (dir1 == NONE || dir2 == NONE) {
        return false;
    }
    
    return (dir1 == UP && dir2 == DOWN) ||
           (dir1 == DOWN && dir2 == UP) ||
           (dir1 == LEFT && dir2 == RIGHT) ||
           (dir1 == RIGHT && dir2 == LEFT);
}

void AdvancedInputHandler::sendDirectionChange(Direction direction)
{
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    
    // === 启动防抖动定时器 ===
    m_debounceTimer->setInterval(m_debounceInterval);
    m_debounceTimer->start();
    
    m_lastSentDirection = direction;
    m_lastSendTime = currentTime;
    
    qDebug() << "AdvancedInputHandler: 发送方向改变" << direction;
    emit directionChanged(direction);
}

void AdvancedInputHandler::predictMovement(Direction direction)
{
    if (!m_inputPrediction) {
        return;
    }
    
    // === 简单的预测逻辑 ===
    float confidence = 0.8f;  // 基础置信度
    
    // 如果与上次方向相同，提高置信度
    if (direction == m_lastSentDirection) {
        confidence = 0.9f;
    }
    
    // 如果是反向移动，降低置信度
    if (isOppositeDirection(direction, m_lastSentDirection)) {
        confidence = 0.1f;
    }
    
    m_predictedDirection = direction;
    
    qDebug() << "AdvancedInputHandler: 预测移动" << direction << "置信度:" << confidence;
    emit inputPredicted(direction, confidence);
}

void AdvancedInputHandler::processInputQueue()
{
    // 处理输入队列中的事件
    while (!m_inputQueue.isEmpty()) {
        InputEvent event = m_inputQueue.dequeue();
        if (!event.processed) {
            sendDirectionChange(event.direction);
        }
    }
}
